package com.example.mardan_demo1.service.impl;

import com.example.mardan_demo1.mapper.AnnouncementMapper;
import com.example.mardan_demo1.mapper.FileUploadMapper;
import com.example.mardan_demo1.pojo.Announcement.Announcement;
import com.example.mardan_demo1.pojo.FilePojo;
import com.example.mardan_demo1.pojo.PageBean;
import com.example.mardan_demo1.pojo.Result;
import com.example.mardan_demo1.pojo.file.Img;
import com.example.mardan_demo1.service.FileUploadService;
import com.example.mardan_demo1.utils.ThreadLocalUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Service
public class FileUploadServiceImpl implements FileUploadService {

    @Autowired
    private FileUploadMapper fileUploadMapper;
    @Autowired
    private AnnouncementMapper announcementMapper;
    @Override
    public Boolean fileUpload(FilePojo filePojo) {
        fileUploadMapper.add(filePojo);
        return true;
    }

    @Override
    public PageBean<FilePojo> list(Integer pageNum, Integer pageSize, String name) {
//    创建PageBean对象
        PageBean<FilePojo> pageBean = new PageBean<>();
//     开启分页查询，自动拼接到sql语句中，不需要在sql中手动写入
        PageHelper.startPage(pageNum, pageSize);
//        调用Mapper
        Map<String, Object> map = ThreadLocalUtil.get();
        System.out.println(name);
        List<FilePojo> as = fileUploadMapper.list(name);
        Page<FilePojo> p = (Page<FilePojo>) as;
//        把数据填充到pageBean对象中
        pageBean.setTotal(p.getTotal());
        pageBean.setItems(p.getResult());
        System.out.println(pageBean);
        return pageBean;
    }

    public Result gongGaoXinZeng(Announcement announcement) {
        Map<String, Object> userInfo = ThreadLocalUtil.get();
        Integer userId = (Integer) userInfo.get("id");
        System.out.println("is hidden" );
        announcement.setCreator(userId.toString());
        announcementMapper.add(announcement);
        return Result.success();
    }
    public Result gongGaoShanChuById(Integer id) {
        announcementMapper.deleteById(id);
        return Result.success("删除成功");
    }
    public Result getGongGaoList(String title, Integer pageNum, Integer pageSize) {
        PageBean<Announcement> pb = new PageBean<>();
        PageHelper.startPage(pageNum, pageSize);
        List<Announcement> as = announcementMapper.getGongGaoList(title);
        Page<Announcement> p = (Page<Announcement>) as;
        pb.setItems(p.getResult());
        pb.setTotal(p.getTotal());
        return Result.success(pb);
    }
    public Result getGongGaoById(Integer id){
        Announcement announcement = announcementMapper.getById(id);
        return Result.success(announcement);
    }
    public Result gongGaoUpdateById(Announcement announcement) {
        Map<String, Object> userInfo = ThreadLocalUtil.get();
        Integer userId = (Integer) userInfo.get("id");
        announcement.setCreator(userId.toString());
        announcementMapper.updateById(announcement);
        return Result.success("操作成功");
    }
    public Result gongGaoHiddenById(Integer id, Integer hidden){
        Announcement announcement = announcementMapper.getById(id);
        Boolean b = false;
        if(hidden == 0) {
            b = false;
        } else if(hidden == 1) {
            b =true;
        } else {
            return Result.error("参数hidden值有误");
        }
        announcement.setHidden(b);
        System.out.println("hidden value:" + announcement);
        announcementMapper.updateHiddenById(id, b);
        return Result.success("操作成功");
    }
    public Result getUserGongGaoList(String title, Integer pageNum, Integer pageSize){
        PageBean<Announcement> pb = new PageBean<>();
        PageHelper.startPage(pageNum, pageSize);
        List<Announcement> as = announcementMapper.getUserGongGaoList(title);
        Page<Announcement> p = (Page<Announcement>) as;
        pb.setItems(p.getResult());
        pb.setTotal(p.getTotal());
        return Result.success(pb);
    }

    @Override
    public Result uploadImg(MultipartFile file) {
        if(file.isEmpty()) {
            return Result.error("上传图片不能为空");
        }
        try {
            // 获取文件名
            String fileName = file.getOriginalFilename();
            // 获取文件类型
            String fileType = file.getContentType();
            // 获取文件大小 转换成mb
            String fileSize = String.valueOf(file.getSize());
            fileSize = String.format("%.2f", Double.parseDouble(fileSize) / 1024 / 1024) + "MB";
            // 生成唯一的文件名，避免覆盖
            String uniqueFileName = System.currentTimeMillis() + "-" + fileName;
            // 上传路径
            String UPLOAD_DIR = "/home/oracle/uploadfiles";
            if (System.getProperty("os.name").toLowerCase().contains("windows")) {
                UPLOAD_DIR = "D:\\files\\";
            } else {
                UPLOAD_DIR = "/home/oracle/uploadfiles";
            }
            //      指定上传目录
            String uploadDirPath = UPLOAD_DIR;
            //确保上传目录存在
            File uploadDir = new File(uploadDirPath);
            if (!uploadDir.exists()) {
                boolean dirsCreate = uploadDir.mkdirs();
                if (!dirsCreate) {
                    return Result.error("创建上传目录失败");
                }
            }
            //获取上传文件的原始文件名
            String originalFilename = file.getOriginalFilename();
            if (originalFilename == null || originalFilename.isEmpty()) {
                return Result.error("文件名不存在");
            }
            //        生成随机数改造文件名称
            String randomName = UUID.randomUUID().toString();
            //        构造保存文件的完整路径
            String filePath = Paths.get(uploadDirPath, randomName + originalFilename).toString();
            String returnFilePath = Paths.get(randomName + originalFilename).toString();
            file.transferTo(new File(filePath));
            System.out.println("file " + filePath + "--------------------------------");
            // 创建img实体类
            Img img = new Img();
            img.setName(fileName);
            img.setType(fileType);
            img.setSize(fileSize);
            img.setCreate_time(LocalDateTime.now().toString());
            img.setDescription(uniqueFileName);
            img.setUrl(filePath);
            // 图片信息存储到数据库
             Boolean isSuccess = fileUploadMapper.uploadImg(img);
             if(isSuccess) {
                 return Result.success(img);
             }

        }catch (IOException e){
            e.printStackTrace();
            return Result.error(e.getMessage());
        }
        return Result.error("出现异常");
    }
}
